#include "smartpagenumberselector.h"
#include <QApplication>
#include <QScreen>
#include <QToolTip>
#include <QCursor>
#include <QKeyEvent>
#include <QtMath>
#include <memory>

SmartPageNumberSelector::SmartPageNumberSelector(QWidget *parent)
    : QWidget(parent)
    , m_previewTimer(new QTimer(this))
{
    setMinimumHeight(240);
    setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
    setMouseTracking(true);
    setCursor(Qt::PointingHandCursor);
    setFocusPolicy(Qt::ClickFocus);

    // 物理渲染器已移除，使用网格系统直接管理位置

    // 设置预览更新定时器
    m_previewTimer->setSingleShot(true);
    m_previewTimer->setInterval(PREVIEW_DELAY_MS);
    connect(m_previewTimer, &QTimer::timeout, this, &SmartPageNumberSelector::onDelayedPreviewUpdate);

}

void SmartPageNumberSelector::setPageNumberSettings(const ProcessingSettings::PageNumberSettings& settings)
{

    if (m_settings.enabled != settings.enabled ||
        m_settings.format != settings.format ||
        m_settings.font != settings.font ||
        m_settings.color != settings.color ||
        m_settings.rotation != settings.rotation ||
        m_settings.opacity != settings.opacity ||
        m_gridSystem.getGridState(m_selectedPosition) != settings.gridState) {


        // 保持用户选择的位置，只更新其他设置
        ProcessingSettings::PageNumberSettings newSettings = settings;
        newSettings.position = m_selectedPosition;
        newSettings.gridState = m_gridSystem.getGridState(m_selectedPosition);

        m_settings = newSettings;
        m_previewTimer->start();
    } else if (m_settings.position != settings.position ||
               m_gridSystem.getGridState(m_selectedPosition) != settings.gridState) {

        m_settings = settings;

        // 更新网格系统状态和选中位置
        m_gridSystem.setGridState(settings.position, settings.gridState);
        m_selectedPosition = settings.position;

        m_previewTimer->start();
    } else {
    }
}

void SmartPageNumberSelector::setProcessingSettings(const ProcessingSettings& settings)
{

    // 只缓存设置用于预览，实际渲染由UnifiedPageRenderer统一处理
    m_processingSettings = settings;

    // 取消可能正在等待的预览更新定时器
    if (m_previewTimer && m_previewTimer->isActive()) {
        m_previewTimer->stop();
    }

    // 只更新页码设置用于预览显示
    setPageNumberSettings(settings.pageNumber);

    // 统一刷新机制：不再立即重绘，等待统一渲染器的结果
    // update(); // 移除立即重绘，避免双重渲染
}

ProcessingSettings::PageNumberSettings SmartPageNumberSelector::getPageNumberSettings() const
{
    ProcessingSettings::PageNumberSettings settings = m_settings;
    settings.position = m_selectedPosition;
    settings.gridState = m_gridSystem.getGridState(m_selectedPosition);


    return settings;
}

void SmartPageNumberSelector::setSamplePage(int currentPage, int totalPages)
{
    if (m_currentPage != currentPage || m_totalPages != totalPages) {
        m_currentPage = currentPage;
        m_totalPages = totalPages;
        update();
    } else {
    }
}

void SmartPageNumberSelector::setPageColor(const QColor& color)
{
    if (m_pageColor != color) {
        m_pageColor = color;
        update();
    }
}

void SmartPageNumberSelector::setHoverColor(const QColor& color)
{
    if (m_hoverColor != color) {
        m_hoverColor = color;
        update();
    }
}

void SmartPageNumberSelector::setSelectedColor(const QColor& color)
{
    if (m_selectedColor != color) {
        m_selectedColor = color;
        update();
    }
}

QRectF SmartPageNumberSelector::getPageRect() const
{
    qreal aspectRatio = 210.0 / 297.0; // A4纸张比例

    // 使用固定的Widget边距，不再依赖ProcessingSettings中的边距
    // SmartPageNumberSelector只用于页码位置选择，不需要显示边距效果
    qreal margin = 20.0; // 固定边距，给页面留出一些空间
    qreal availableWidth = width() - 2 * margin;
    qreal availableHeight = height() - 2 * margin;

    qreal pageWidth, pageHeight;

    if (availableWidth / availableHeight > aspectRatio) {
        pageHeight = availableHeight;
        pageWidth = pageHeight * aspectRatio;
    } else {
        pageWidth = availableWidth;
        pageHeight = pageWidth / aspectRatio;
    }

    qreal pageX = margin + (availableWidth - pageWidth) / 2;
    qreal pageY = margin + (availableHeight - pageHeight) / 2;

    return QRectF(pageX, pageY, pageWidth, pageHeight);
}

void SmartPageNumberSelector::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event)

    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);

    // 简化的绘制流程
    drawPageBackground(painter);
    drawCenterIndicators(painter);
    drawPositionZones(painter);
    drawPageNumber(painter);
    drawHoverEffect(painter);

    // 显示当前位置的网格点（如果正在拖动或鼠标悬停）
    if (m_isDragging || m_showGridPoints) {
        drawGridPoints(painter, m_selectedPosition);
    }
}

void SmartPageNumberSelector::mousePressEvent(QMouseEvent *event)
{
    if (event->button() != Qt::LeftButton) return;

    Position clickedPosition = getPositionAtPoint(event->position());

    if (clickedPosition != Position::Custom) {
        m_isPressed = true;
        m_pressedPosition = clickedPosition;
        m_selectedPosition = clickedPosition;
        m_dragStartPosition = event->position();

        // 显示网格点
        m_showGridPoints = true;


        update();
        emit positionChanged(m_selectedPosition);
    }
}

void SmartPageNumberSelector::mouseMoveEvent(QMouseEvent *event)
{
    if (!m_isPressed) {
        // 悬停检测
        Position hoveredPosition = getPositionAtPoint(event->position());

        if (m_hoveredPosition != hoveredPosition) {
            m_hoveredPosition = hoveredPosition;
            updateCursor(event->position());
            update();
        }
        return;
    }

    // 拖动逻辑
    if (!m_isDragging) {
        double dragDistance = QLineF(m_dragStartPosition, event->position()).length();
        if (dragDistance > 5) { // 5像素拖动阈值
            m_isDragging = true;
        }
    }

    if (m_isDragging) {
        // 将鼠标位置吸附到最近的网格点
        GridPageNumberSystem::GridState newGridState = snapToGrid(m_selectedPosition, event->position());

        if (m_gridSystem.getGridState(m_selectedPosition) != newGridState) {
            m_gridSystem.setGridState(m_selectedPosition, newGridState);


            update();
            emit gridStateChanged(m_selectedPosition, newGridState);
            m_previewTimer->start();
        }
    }
}

void SmartPageNumberSelector::mouseReleaseEvent(QMouseEvent *event)
{
    Q_UNUSED(event)

    if (m_isDragging) {
    }

    m_isPressed = false;
    m_isDragging = false;
    m_showGridPoints = false;

    update();
}

void SmartPageNumberSelector::mouseDoubleClickEvent(QMouseEvent *event)
{
    Position clickedPosition = getPositionAtPoint(event->position());

    if (clickedPosition != Position::Custom) {
        // 双击重置到网格中心
        resetGridToCenter(clickedPosition);


        update();
        emit gridStateChanged(clickedPosition, GridPageNumberSystem::GridState());
        m_previewTimer->start();
    }
}

void SmartPageNumberSelector::leaveEvent(QEvent *event)
{
    Q_UNUSED(event)


    // 重置悬停状态，取消悬停效果
    m_hoveredPosition = Position::Custom; // 设置为Custom以避免任何区域的高亮
    m_showGridPoints = false;
    setCursor(Qt::ArrowCursor);
    update();
}

void SmartPageNumberSelector::onDelayedPreviewUpdate()
{
    // Martin Fowler重构：简化信号触发机制
    // 只触发位置预览信号，不触发设置变化信号
    // 设置变化由SettingsWidget统一管理，避免重复信号

    // 计算当前选中位置的实际像素坐标
    QPointF pixelPosition = gridToPixelPosition(m_selectedPosition,
                                              m_gridSystem.getGridState(m_selectedPosition));

    update();
    emit pagePositionPreviewChanged(pixelPosition);
    
    // 不再直接触发settingsChanged信号，避免与SettingsWidget的onSettingsChanged冲突
    // emit settingsChanged(updatedSettings);
}

// ===================== 简化的绘制方法实现 =====================

void SmartPageNumberSelector::drawPageBackground(QPainter& painter)
{
    QRectF pageRect = getPageRect();

    painter.setBrush(m_pageColor);
    painter.setPen(QPen(QColor(200, 200, 200), 1));
    painter.drawRect(pageRect);

    // 绘制页面阴影
    QRectF shadowRect = pageRect.translated(2, 2);
    painter.setBrush(QColor(0, 0, 0, 30));
    painter.setPen(Qt::NoPen);
    painter.drawRect(shadowRect);
}

void SmartPageNumberSelector::drawCenterIndicators(QPainter& painter)
{
    QRectF pageRect = getPageRect();

    painter.setPen(QPen(QColor(200, 200, 200), 1, Qt::DotLine));
    painter.setBrush(Qt::NoBrush);

    // 绘制中心线
    painter.drawLine(pageRect.center().x(), pageRect.top(),
                    pageRect.center().x(), pageRect.bottom());
    painter.drawLine(pageRect.left(), pageRect.center().y(),
                    pageRect.right(), pageRect.center().y());
}

void SmartPageNumberSelector::drawPositionZones(QPainter& painter)
{
    for (Position pos : PagePositionSystem::getPresetPositions()) {
        QRectF zone = getPositionZone(pos);

        // 确定区域颜色
        QColor zoneColor = m_zoneColor;
        QPen pen = QPen(zoneColor.darker(120), 1);

        if (pos == m_hoveredPosition) {
            zoneColor = m_hoverColor;
            pen = QPen(zoneColor.darker(120), 2);
        }
        if (pos == m_selectedPosition) {
            zoneColor = m_selectedColor;
            zoneColor.setAlpha(80);
            // 选中状态使用更粗、更明显的边框
            pen = QPen(m_selectedColor.darker(150), 3);
            pen.setStyle(Qt::SolidLine);
        }

        painter.setBrush(zoneColor);
        painter.setPen(pen);
        painter.drawRoundedRect(zone, 3, 3);
    }
}

void SmartPageNumberSelector::drawPageNumber(QPainter& painter)
{
    if (!m_settings.enabled) return;

    
    QString pageNumberText = m_settings.formatPageNumber(m_currentPage, m_totalPages);

    painter.save();
    painter.setFont(m_settings.font);
    painter.setPen(m_settings.color);
    painter.setOpacity(m_settings.opacity);

    // 使用网格系统计算实际位置
    QPointF pageNumberPos = gridToPixelPosition(m_selectedPosition,
                                              m_gridSystem.getGridState(m_selectedPosition));

    // 应用旋转
    if (qAbs(m_settings.rotation) > 0.1) {
        painter.translate(pageNumberPos);
        painter.rotate(m_settings.rotation);
        painter.translate(-pageNumberPos);
    }

    painter.drawText(pageNumberPos, pageNumberText);
    painter.restore();

}

void SmartPageNumberSelector::drawHoverEffect(QPainter& painter)
{
    // 只有在悬停位置有效且不是选中位置时才绘制悬停效果
    if (m_hoveredPosition == Position::Custom || m_hoveredPosition == m_selectedPosition) return;

    QRectF zone = getPositionZone(m_hoveredPosition);

    painter.setBrush(Qt::NoBrush);
    painter.setPen(QPen(m_selectedColor, 2));
    painter.drawRoundedRect(zone.adjusted(-1, -1, 1, 1), 4, 4);
}

void SmartPageNumberSelector::drawGridPoints(QPainter& painter, Position position)
{
    QList<QPointF> gridPoints = getGridPositions(position);
    GridPageNumberSystem::GridState currentState = m_gridSystem.getGridState(position);
    QPointF currentPos = gridToPixelPosition(position, currentState);

    painter.setBrush(QColor(0, 122, 255, 100));
    painter.setPen(QPen(QColor(0, 122, 255), 1));

    for (const QPointF& point : gridPoints) {
        qreal size = (QLineF(point, currentPos).length() < 1.0) ? 8 : 5; // 当前位置更大
        painter.drawEllipse(point, size/2, size/2);
    }
}

// ===================== 网格系统相关方法实现 =====================

QPointF SmartPageNumberSelector::getBasePositionInPixels(Position position) const
{
    QRectF pageRect = getPageRect();
    qreal zoneSize = m_zoneSize;

    switch (position) {
        case PagePositionSystem::Position::TopLeft:
            return QPointF(pageRect.left() + zoneSize/2, pageRect.top() + zoneSize/2);
        case PagePositionSystem::Position::TopCenter:
            return QPointF(pageRect.center().x(), pageRect.top() + zoneSize/2);
        case PagePositionSystem::Position::TopRight:
            return QPointF(pageRect.right() - zoneSize/2, pageRect.top() + zoneSize/2);
        case PagePositionSystem::Position::BottomLeft:
            return QPointF(pageRect.left() + zoneSize/2, pageRect.bottom() - zoneSize/2);
        case PagePositionSystem::Position::BottomCenter:
            return QPointF(pageRect.center().x(), pageRect.bottom() - zoneSize/2);
        case PagePositionSystem::Position::BottomRight:
            return QPointF(pageRect.right() - zoneSize/2, pageRect.bottom() - zoneSize/2);
        default:
            return pageRect.center();
    }
}

GridPageNumberSystem::GridState SmartPageNumberSelector::snapToGrid(Position position, const QPointF& pixelPosition) const
{
    return m_gridSystem.snapToNearestGrid(getPageRect(), position, pixelPosition);
}

QPointF SmartPageNumberSelector::gridToPixelPosition(Position position, const GridPageNumberSystem::GridState& gridState) const
{
    return m_gridSystem.calculateGridPosition(getPageRect(), position, gridState);
}

QList<QPointF> SmartPageNumberSelector::getGridPositions(Position position) const
{
    return m_gridSystem.getReachableGridPoints(getPageRect(), position);
}

void SmartPageNumberSelector::resetGridToCenter(Position position)
{
    m_gridSystem.resetToCenter(position);
}

// ===================== 位置计算和工具方法 =====================

QRectF SmartPageNumberSelector::getPositionZone(Position position) const
{
    QPointF center = getBasePositionInPixels(position);
    qreal size = m_zoneSize;

    return QRectF(center.x() - size/2, center.y() - size/2, size, size);
}

QPointF SmartPageNumberSelector::calculatePageNumberPosition(Position position) const
{
    return getBasePositionInPixels(position);
}

PagePositionSystem::Position SmartPageNumberSelector::getPositionAtPoint(const QPointF& point) const
{
    for (Position pos : PagePositionSystem::getPresetPositions()) {
        QRectF zone = getPositionZone(pos);
        if (zone.contains(point)) {
            return pos;
        }
    }
    return Position::Custom;
}

void SmartPageNumberSelector::updateCursor(const QPointF& mousePos)
{
    Position position = getPositionAtPoint(mousePos);

    if (position != Position::Custom) {
        setCursor(Qt::PointingHandCursor);
    } else {
        setCursor(Qt::ArrowCursor);
    }
}

QString SmartPageNumberSelector::getPositionName(Position position) const
{
    return PagePositionSystem::getDisplayName(position);
}

